// var uri = 'http://localhost'
var uri = 'https://survey.utils.win'

let sites = [
    '', '', '', '/signIn',
    '', '', '', '/aboutUs',
    '', '', '', '/contactUs',
    '', '', '', '/privacyPolicy',
    '', '', '', '/termsOfUse',
    '', '', '', '/signUp',
    '', '', ''
];


var countryCode = 'us'
var countryRegion = ''

// 生成一个随机索引
function getRandomIndex(array) {
    return Math.floor(Math.random() * sites.length);
}

// 从数组中随机取出一个元素
function getSite(open_urls) {
    const randomIndex = getRandomIndex(sites);
    if (open_urls) {
        return uri + sites[randomIndex] + '?url=' + encodeURIComponent(open_urls);
    } else {
        return uri + sites[randomIndex];
    }
}

// $('.cre-all-btn').on('click', function(e) {
//     e.preventDefault(); // 阻止链接默认行为
//     $(this).hide();
//     $('.cre-all-loading').show();
//     creUser(results1, 0);
// });
// async function creUser(results, index) {
//     console.log(index);
//     await new Promise(resolve => setTimeout(resolve, 2000));
//     var result = results[index];
//     if (!result.user_id && result.name) {
//         create_adspower(result.name, null, "https://survey.utils.win/bitLabs/newUser2");
//     }
//     if (index < results.length - 1 && index < 5) {
//         creUser(results, index + 1);
//     } else {
//         await new Promise(resolve => setTimeout(resolve, 1500));
//         fetchDataAndShow(); // 刷新页面
//         $('.cre-all-loading').hide();
//         $('.cre-all-btn').show();
//     }
// }


$('.delete-all-btn').on('click', function(e) {
    e.preventDefault(); // 阻止链接默认行为
    $(this).hide();
    $('.delete-all-loading').show();
    var userIds = results1.map(item => item.user_id ? item.user_id : undefined).filter(item => item !==
        undefined);
    console.log(userIds);
    stopUser(userIds, 0);
});
async function stopUser(userIds, index) {
    console.log(index);
    await new Promise(resolve => setTimeout(resolve, 1100));
    $.ajax({
        url: "http://127.0.0.1:50325/api/v1/browser/stop?user_id=" + userIds[index],
        type: 'GET',
        contentType: 'application/json',
        success: function(response) {
            console.log('关闭成功:', response);
            if (index < userIds.length - 1) {
                stopUser(userIds, index + 1);
            } else {
                deleteUser(userIds);
            }
        },
        error: function(xhr, status, error) {
            console.error('关闭失败:', xhr, status, error);
        }
    });
}
async function deleteUser(userIds) {
    await new Promise(resolve => setTimeout(resolve, 1100));
    var json_data = {
        "user_ids": userIds
    };
    console.log(json_data);
    $.ajax({
        url: "http://127.0.0.1:50325/api/v1/user/delete",
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(json_data),
        success: function(response) {
            console.log('删除成功:', response);
            fetchDataAndShow(); // 刷新页面
        },
        error: function(xhr, status, error) {
            console.error('删除失败:', xhr, status, error);
        }
    });
}
// 

var $newTd = $(
    '<td colspan="8"><div class="d-flex justify-content-center"><div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div></div></dt>'
);

function fetchDataAndShow() {

    $('#dataTable > tbody').empty();
    // 定义两个 AJAX 请求
    var request1 = $.ajax({
        url: "http://127.0.0.1:50325/api/v1/user/list?page_size=100&group_id=4831294",
        type: 'GET',
        dataType: 'json'
    });

    $('#dataTable > tbody').empty();

    // 使用 $.when() 等待两个请求都完成
    $.when(request1).done(function(data1) {
        results1 = data1.data.list

        var $table = $('#dataTable > tbody');
        // 遍历 port 数组
        var port = ['28001', '28002', '28003', '28004', '28005', '28006', '28007', '28008', '28009', '28010'];
        $.each(port, function(index, portItem) {
            // 检查 date 数组中是否已经有对应的对象
            var found = false;
            $.each(results1, function(resultIndex, resultItem) {

                if (resultItem.name === portItem) {
                    found = true;

                    return false; // 跳出内部循环
                }
            });
            // 如果 date 中没有对应的对象，则添加到 result
            if (!found) {
                results1.push({
                    "name": portItem
                });
            }
        });

        // 显示结果
        showResults(results1);
        $('.delete-all-loading').hide();
        $('.delete-all-btn').show();
    }).fail(function(jqXHR1, jqXHR2) {
        // 一个或两个请求失败时执行
        console.error('Error fetching data:', jqXHR1, jqXHR2);
    });
}

// 显示结果的函数
function showResults(results) {

    results.sort(function(a, b) {
        return a.name - b.name; // 升序排序
        // 如果需要降序排序，可以改为：
        // return b.name - a.name;
    });
    // 将结果渲染到页面上，例如使用 JSON.stringify 将结果转换为字符串
    var $table = $('#dataTable > tbody');

    $.each(results, function(index, resultItem) {
        var $row = $('<tr ></tr>');
        $row.append($('<td>-</td>').text(resultItem.name));
        $row.append($('<td>-</td>').text(resultItem.serial_number));
        $row.append($('<td><a href="#">-</a></td>').text(resultItem.remark));
        $row.append($('<td><a href="#">-</a></td>').text(resultItem.pid));
        if (resultItem.serial_number) {
            $row.append($('<td><a href="#" style="color:red" class="delete_link_' + resultItem.name +
                '">删除</a></td>'));
            $row.append($('<td><a id="a1_' + resultItem.name +
                '" href="#" style="color:red" class="open_link_' + resultItem.name + '">启动</a></td>'));
        } else {
            $row.append($('<td><a href="#" class="create_link_ads_new_' + resultItem.name +
                '">新用户</a></td>'));
            $row.append($('<td><a href="#" class="create_link_ads_nul_' + resultItem.name +
                '">无用户</a></td>'));
        }
        // 为所有创建链接绑定点击事件
        $table.append($row);
        $('.create_link_ads_new_' + resultItem.name).on('click', function(e) {
            e.preventDefault(); // 阻止链接默认行为
            open_urls = uri + "/bitlabs/user"

            create_adspower(resultItem.name, $(this), getSite(open_urls), 'new');
        });

        $('.create_link_ads_nul_' + resultItem.name).on('click', function(e) {
            e.preventDefault(); // 阻止链接默认行为
            open_urls = ""
            create_adspower(resultItem.name, $(this), getSite(open_urls), '无用户');
        });

        $('.delete_link_' + resultItem.name).on('click', function(e) {
            e.preventDefault(); // 阻止链接默认行为
            delete_adspower(resultItem.user_id, $(this)); // 调用你的函数
        });

        $('.open_link_' + resultItem.name).on('click', function(e) {
            e.preventDefault(); // 阻止链接默认行为
            open_adspower(resultItem.user_id, $(this)); // 调用你的函数
        });
    })
}


function create_adspower(port, element, open_urls, open_type) {
    if (element) {
        var $tr = element.closest('tr');
        $tr.empty();
        // 将新的 'td' 元素添加到 'tr' 元素中
        $tr.append($newTd);
    }

    const CHAR_SET = "abcdefghijklmnopqrstuvwxyz0123456789";
    RANDOM_STR = ""
    // 循环生成 6 位随机字符串
    for (let i = 0; i < 6; i++) {
        const randomIndex = Math.floor(Math.random() * CHAR_SET.length);
        RANDOM_STR += CHAR_SET[randomIndex];
    }

    var st = ""
    if (countryRegion) {
        st = '-st-' + countryRegion;
    }

    var input_city = $('input[type="text"][id="input_city"]').val();
    var city = ""
    if (input_city) {
        city = '-city-' + input_city.replace(/\s/g, '');
    }

    proxy_type = "socks5"
    proxy_host = "proxy.ipidea.io"
    proxy_port = 2333
    proxy_user = `zhiwu0909-zone-custom-region-${countryCode}${st}${city}-session-${RANDOM_STR}-sessTime-120`
    proxy_password = "zhiwu090901"

    console.log(proxy_user)
    var json_data = {
        "open_urls": [open_urls],
        "group_id": "4831294",
        "name": port,
        "remark": countryCode + "-" + open_type,
        "user_proxy_config": {
            "proxy_type": proxy_type,
            "proxy_host": proxy_host,
            "proxy_port": proxy_port,
            "proxy_soft": "other",
            "proxy_user": proxy_user,
            "proxy_password": proxy_password
        },
        "fingerprint_config": {
            "automatic_timezone": "1",
            "webrtc": "proxy",
            "language_switch": "1",
            "screen_resolution": "none",
            "canvas": "1",
            "webgl_image": "1",
            "webgl": "3",
            "audio": "1",
            "media_devices": "1",
            "client_rects": "1",
            "device_name_switch": "1",
            "random_ua": {
                "ua_browser": ["chrome"],
                "ua_system_version": ["Windows 10", "Windows 11"]
            },
            "speech_switch": "1",
            "browser_kernel_config": {
                "version": "ua_auto",
                "type": "chrome"
            },
            "fonts": ["all"]
        }
    }
    create_adspower_net(json_data, element);
}

function create_adspower_net(json_data, element) {
    $.ajax({
        url: "http://127.0.0.1:50325/api/v1/user/create",
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(json_data), // 假设 rowData 是你想发送的 JSON 数据
        success: function(response) {
            console.log('创建成功:', response);
            if (element) {
                fetchDataAndShow(); // 刷新页面
            }
        },
        error: function(xhr, status, error) {
            console.error('创建失败:', xhr, status, error);
        }
    });
}


function delete_adspower(user_id, element) {
    var $tr = element.closest('tr');
    $tr.empty();
    // 将新的 'td' 元素添加到 'tr' 元素中
    $tr.append($newTd);
    // 发送 POST 请求到服务器
    var json_data = {
        "user_ids": [user_id]
    }
    $.ajax({
        url: "http://127.0.0.1:50325/api/v1/user/delete",
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(json_data), // 假设 rowData 是你想发送的 JSON 数据
        success: function(response) {
            console.log('删除成功:', response);
            fetchDataAndShow(); // 刷新页面

            // 这里可以更新表格或进行其他操作
        },
        error: function(xhr, status, error) {
            console.error('删除失败:', xhr, status, error);
        }
    });
}


function open_adspower(user_id, element) {
    var $tr = element.closest('tr');
    $tr.empty();
    // 将新的 'td' 元素添加到 'tr' 元素中
    $tr.append($newTd);
    // 发送 POST 请求到服务器
    var json_data = {
        "user_ids": [user_id]
    }
    $.ajax({
        url: "http://127.0.0.1:50325/api/v1/browser/start?new_first_tab=1&user_id=" + user_id,
        type: 'GET',
        contentType: 'application/json',
        data: JSON.stringify(json_data), // 假设 rowData 是你想发送的 JSON 数据
        success: function(response) {
            console.log('启动成功:', response);
            fetchDataAndShow(); // 刷新页面

            // 这里可以更新表格或进行其他操作
        },
        error: function(xhr, status, error) {
            console.error('启动失败:', xhr, status, error);
        }
    });
}

// 调用函数
$(document).ready(function() {
    // 遍历 countryMap 数组
    var options = '';
    for (let i = 0; i < countryMap.length; i++) {
        const country = countryMap[i];
        console.log(`国家代码: ${country.code}, 国家名称: ${country.name}`);
        options += '<option text="' + country.code + '" value="' + country.code + '"> ' + country.name + '(' +
            country.code + ') </option>';
        // 遍历 child 数组
        if (i == 0) {
            countryCode = country.code;
            var options0 = '<option text="" value=""> 不限 </option>';
            for (const child of country.child) {
                options0 += '<option text="' + child.code + '" value="' + child.code + '"> ' + child
                    .name + '(' + child.code + ') </option>';
            }
            $('#country_region').html(options0);
        }
    }
    $('#country_code').html(options);

    $('#country_code').on('change', function() {
        // 获取选中的值
        countryCode = $(this).val();

        for (const country of countryMap) {
            if (countryCode == country.code) {
                var options0 = '<option text="" value=""> 不限 </option>';
                for (const child of country.child) {
                    options0 += '<option text="' + child.code + '" value="' + child.code + '"> ' + child
                        .name + '(' + child.code + ') </option>';
                }
                $('#country_region').html(options0);
                break;
            }
        }
    });

    $('#country_region').on('change', function() {
        // 获取选中的值
        countryRegion = $(this).val();
    });
    // 定义 端口
    fetchDataAndShow();
});